// pages/cart/index/index.js
const api = require('../../../api/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    saveHidden: true,
    totalPrice: 0,
    allSelect: false,
    noSelect: true,
    cartGoods: [],
    inventory: 99999,
    cartNum: "",
    delBtnWidth: 120,
    isLogin: wx.getStorageSync("isLogin"),
    index: 0
  },

  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },

  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    this.initEleWidth();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    that.setData({
      isLogin: wx.getStorageSync("isLogin")
    });
    that.getCartList();
  },

  touchStart: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },

  touchMove: function(e) {
    var index = e.currentTarget.dataset.index;

    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      } else if (disX > 0) { //移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          left = "left:-" + delBtnWidth + "px";
        }
      }
      var cartGoods = this.data.cartGoods;
      if (index != "" && index != null) {
        cartGoods[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), cartGoods);
      }
    }
  },

  touchEnd: function(e) {
    var index = e.currentTarget.dataset.index;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      var cartGoods = this.data.cartGoods;
      if (index !== "" && index != null) {
        cartGoods[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), cartGoods);

      }
    }
  },

  toLoginTap: function() {
    wx.navigateTo({
      url: '../../login/login/login',
    })
  },

  toShopTap: function () {
    wx.navigateTo({
      url: '/pages/home/index/index',
    })
  },

  deleteTap: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var cartGoods = that.data.cartGoods;
    if (index !== "" && index != null) {
      var goodsId = cartGoods[parseInt(index)].id;
      wx.request({
        url: api.CartDelete,
        data: {
          good: goodsId
        },
        method: "POST",
        header: {
          'Content-Type': 'application/json',
          'X-bocang-Authorization': wx.getStorageSync('token')
        },
        success: function(res) {
          if (res.data.error_code === 0) {
            that.getCartList();
          }
          // else {
          //   wx.navigateTo({
          //     url: '../../login/login/login',
          //   });
          // }
        }
      });
    }
  },

  getCartList: function() {
    let that = this;
    wx.showLoading({
      "mask": true,
      title: '加载中...'
    });
    wx.request({
      url: api.CartGet,
      data: {

      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        console.log("success");
        if (res.data.error_code === 0) {
          if (res.data.goods_groups.length > 0 && res.data.goods_groups[0].goods) {
            that.setData({
              cartGoods: res.data.goods_groups[0].goods,
              index: res.data.goods_groups[0].goods.length
            });
          } else {
            that.setData({
              cartGoods: []
            });
          }
          this.onShow();
        }
        // else {
        //   wx.navigateTo({
        //     url: '../../login/login/login',
        //   });
        // }
      },
    });
  },

  selectTap: function(e) {
    var index = e.currentTarget.dataset.index;
    var cartGoods = this.data.cartGoods;
    if (index !== "" && index != null) {
      cartGoods[parseInt(index)].active = !cartGoods[parseInt(index)].active;
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), cartGoods);
    }
  },

  totalPrice: function() {
    var cartGoods = this.data.cartGoods;
    var total = 0;
    for (var i = 0; i < cartGoods.length; i++) {
      var curItem = cartGoods[i];
      if (curItem.active) {
        total += parseFloat(curItem.price) * curItem.amount;
      }
    }
    total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
    return total;
  },

  allSelect: function() {
    var cartGoods = this.data.cartGoods;
    var allSelect = false;
    for (var i = 0; i < cartGoods.length; i++) {
      var curItem = cartGoods[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },

  noSelect: function() {
    var cartGoods = this.data.cartGoods;;
    var noSelect = 0;
    for (var i = 0; i < cartGoods.length; i++) {
      var curItem = cartGoods[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == cartGoods.length) {
      return true;
    } else {
      return false;
    }
  },

  getSaveHide: function() {
    var saveHide = this.data.saveHidden;
    return saveHide;
  },

  setGoodsList: function(saveHidden, total, allSelect, noSelect, cartGoods) {
    this.setData({
      saveHidden: saveHidden,
      totalPrice: total,
      allSelect: allSelect,
      noSelect: noSelect,
      cartGoods: cartGoods,
    });

  },

  bindSelectAll: function() {
    var currentAllSelect = this.data.allSelect;
    var cartGoods = this.data.cartGoods;
    if (currentAllSelect) {
      for (var i = 0; i < cartGoods.length; i++) {
        var curItem = cartGoods[i];
        curItem.active = false;
      }
    } else {
      for (var i = 0; i < cartGoods.length; i++) {
        var curItem = cartGoods[i];
        curItem.active = true;
      }
    }
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), cartGoods)
  },

  jianBtnTap: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var cartGoods = this.data.cartGoods;
    var warn_number = cartGoods[parseInt(index)].product.warn_number;
    if (index !== "" && index != null) {
      if (cartGoods[parseInt(index)].amount > warn_number) {
        var goodsId = cartGoods[parseInt(index)].id;
        var amount = cartGoods[parseInt(index)].amount - warn_number;
        that.updateCartGoods(goodsId, amount);
      }
    }
  },

  // bindInputTap: function (e) {
  //   let that = this;
  //   var index = e.currentTarget.dataset.index;
  //   var cartGoods = this.data.cartGoods;
  //   var warn_number = cartGoods[parseInt(index)].product.warn_number;
  //   this.setData({
  //     keyword: e.detail.value
  //   });
  // },

  jiaBtnTap: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var cartGoods = this.data.cartGoods;
    var warn_number = cartGoods[parseInt(index)].product.warn_number;
    if (index !== "" && index != null) {
      var goodsId = cartGoods[parseInt(index)].id;
      var amount = cartGoods[parseInt(index)].amount + warn_number;
      that.updateCartGoods(goodsId, amount);
    }
  },

  updateCartGoods: function(goodsId, amount) {
    let that = this;
    wx.showLoading({
      "mask": true
    });
    wx.request({
      url: api.CartUpdate,
      data: {
        good: goodsId,
        amount: amount
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        console.log("updateCartGoods-SUCCESS");
        if (res.data.error_code === 0) {
          that.getCartList();
        } else {
          wx.navigateTo({
            url: '../../login/login/login',
          });
        }
      },
    })
  },

  editTap: function() {
    var cartGoods = this.data.cartGoods;
    for (var i = 0; i < cartGoods.length; i++) {
      var curItem = cartGoods[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), cartGoods);
  },

  saveTap: function() {
    var cartGoods = this.data.cartGoods;
    for (var i = 0; i < cartGoods.length; i++) {
      var curItem = cartGoods[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), cartGoods);
  },

  deleteSelect: function() {
    let that = this;
    var cartGoods = that.data.cartGoods;
    wx.showLoading({
      "mask": true,
      title: '正在删除...'
    })
    for (var i = 0; i < cartGoods.length; i++) {
      var goodsId = cartGoods[i].id;
      var isActive = cartGoods[i].active;
      if (isActive) {
        wx.request({
          url: api.CartDelete,
          data: {
            good: goodsId
          },
          method: "POST",
          header: {
            'Content-Type': 'application/json',
            'X-bocang-Authorization': wx.getStorageSync('token')
          },
          success: function (res) {
            if (res.data.error_code === 0) {
              
            }
          }
        });
      }
    }
    wx.hideLoading();
    that.getCartList();
  },

  toPayOrder: function () {
    wx.showLoading();
    let that = this;
    if (that.data.noSelect) {
      wx.hideLoading();
      return;
    }

    var settlementGoods = this.data.cartGoods.filter(function (element) {
      if (element.active == true) {
        return true;
      } else {
        return false;
      }
    });
    wx.setStorageSync('settlementGoods', settlementGoods)
    wx.hideLoading();
    wx.navigateTo({
      url: '../confirmorder/confirmorder',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.getCartList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})